/**
 * 智能体创建页面组件
 * 
 * 功能特性：
 * - 智能体创建表单
 * - 模型配置选择
 * - 提示词模板选择
 * - 表单验证
 * - 返回导航
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Select, 
  Button, 
  message, 
  Space, 
  InputNumber,
  Switch,
  Radio,
  Tag,
  Divider
} from 'antd';
import { useNavigate } from 'react-router-dom';
import { SaveOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import agentService, { AgentType } from '@services/agentService';

const { TextArea } = Input;
const { Option } = Select;
const { Group: RadioGroup } = Radio;

interface ModelConfig {
  id: string;
  name: string;
  provider: string;
  model: string;
  isActive: boolean;
}

interface PromptTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  isActive: boolean;
}

const AgentCreate: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [modelConfigs, setModelConfigs] = useState<ModelConfig[]>([]);
  const [promptTemplates, setPromptTemplates] = useState<PromptTemplate[]>([]);

  useEffect(() => {
    loadModelConfigs();
    loadPromptTemplates();
  }, []);

  const loadModelConfigs = async () => {
    try {
      const response = await agentService.getModelConfigs({
        isActive: true,
        maxResultCount: 100,
      });
      setModelConfigs(response.items);
    } catch (error) {
      message.error('加载模型配置失败');
    }
  };

  const loadPromptTemplates = async () => {
    try {
      const response = await agentService.getPromptTemplates({
        isActive: true,
        maxResultCount: 100,
      });
      setPromptTemplates(response.items);
    } catch (error) {
      message.error('加载提示词模板失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      // 确保包含默认的agentType和configuration
      const createData = {
        ...values,
        agentType: values.agentType || AgentType.Chat,
        configuration: values.configuration || '{}',
        tags: values.tags || '',
        maxTokens: values.maxTokens || 4000,
        temperature: values.temperature || 0.7,
        timeoutSeconds: values.timeoutSeconds || 30
      };
      await agentService.createAgent(createData);
      message.success('创建智能体成功');
      navigate('/agents');
    } catch (error) {
      message.error('创建智能体失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card
      title="创建智能体"
      extra={
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/agents')}>
          返回列表
        </Button>
      }
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        autoComplete="off"
      >
        <Form.Item
          name="name"
          label="智能体名称"
          rules={[{ required: true, message: '请输入智能体名称' }]}
        >
          <Input placeholder="请输入智能体名称" />
        </Form.Item>

        <Form.Item
          name="description"
          label="描述"
          rules={[{ required: true, message: '请输入描述' }]}
        >
          <TextArea 
            rows={3} 
            placeholder="请输入智能体描述"
            maxLength={500}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="systemPrompt"
          label="系统提示词"
          rules={[{ required: true, message: '请输入系统提示词' }]}
        >
          <TextArea 
            rows={6} 
            placeholder="请输入系统提示词"
            maxLength={2000}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="modelConfigId"
          label="模型配置"
          rules={[{ required: true, message: '请选择模型配置' }]}
        >
          <Select placeholder="请选择模型配置">
            {modelConfigs.map(config => (
              <Option key={config.id} value={config.id}>
                {config.name} ({config.provider} - {config.model})
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="promptTemplateId"
          label="提示词模板"
        >
          <Select placeholder="请选择提示词模板" allowClear>
            {promptTemplates.map(template => (
              <Option key={template.id} value={template.id}>
                {template.name} ({template.category})
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="agentType"
          label="智能体类型"
          rules={[{ required: true, message: '请选择智能体类型' }]}
          initialValue={AgentType.Chat}
        >
          <RadioGroup>
            {Object.values(AgentType).map(type => (
              <Radio key={type} value={type}>
                <Tag color={
                  type === AgentType.Chat ? 'blue' :
                  type === AgentType.Assistant ? 'green' :
                  type === AgentType.Analyst ? 'orange' :
                  type === AgentType.Creative ? 'purple' : 'default'
                }>
                  {
                    type === AgentType.Chat ? '聊天' :
                    type === AgentType.Assistant ? '助手' :
                    type === AgentType.Analyst ? '分析' :
                    type === AgentType.Creative ? '创意' : '自定义'
                  }
                </Tag>
              </Radio>
            ))}
          </RadioGroup>
        </Form.Item>

        <Divider />

        <Form.Item
          name="maxTokens"
          label="最大Token数"
          rules={[{ required: true, message: '请输入最大Token数' }]}
          initialValue={4000}
        >
          <InputNumber 
            min={1} 
            max={32000}
            style={{ width: '100%' }}
            placeholder="最大Token数"
          />
        </Form.Item>

        <Form.Item
          name="temperature"
          label="温度参数"
          rules={[{ required: true, message: '请输入温度参数' }]}
          initialValue={0.7}
        >
          <InputNumber 
            min={0} 
            max={2}
            step={0.1}
            style={{ width: '100%' }}
            placeholder="温度参数 (0.0-2.0)"
          />
        </Form.Item>

        <Form.Item
          name="timeoutSeconds"
          label="超时时间（秒）"
          rules={[{ required: true, message: '请输入超时时间' }]}
          initialValue={30}
        >
          <InputNumber 
            min={1} 
            max={300}
            style={{ width: '100%' }}
            placeholder="超时时间"
          />
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
        >
          <Input placeholder="请输入标签，用逗号分隔" />
        </Form.Item>

        <Form.Item
          name="isActive"
          label="激活状态"
          valuePropName="checked"
          initialValue={true}
        >
          <Switch checkedChildren="激活" unCheckedChildren="禁用" />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              icon={<SaveOutlined />}
            >
              保存
            </Button>
            <Button onClick={() => navigate('/agents')}>
              取消
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default AgentCreate;